#!/usr/bin/env node
const type = process.argv[2];
const {buildImage, pushImage} = require("./api");
const {compress} = require("./docker-compress");
const fs = require("fs");
const tarName = "Dockerfile";


//读取package.json文件

let package = fs.readFileSync("./package.json",'utf-8');
package = JSON.parse(package);
//检查docker.config是否存在
let isFile = fs.existsSync("./docker-config.json");
if(!isFile) {
    console.log("docker-config.json文件不存在");
}

//读取docker-config.json文件
let config = fs.readFileSync("./docker-config.json",'utf-8');
config = JSON.parse(config);
//检查目录是否存在

let isDir = fs.existsSync("./docker");
if(isDir) {
    //删除目录
    fs.rmdirSync("./docker",{recursive:true});
}

//创建目录
try{
    fs.mkdirSync("./docker");
} catch{
    console.error("目录创建失败")
    return false;
}
const suffix = "tar";
let name = package["docker-registry"].registry + "/" + package.name + ":" + package.version;
const baseUrl = package["docker-registry"].host;

if(type === "build") {
    let file = [
        {file: "Dockerfile" , type: 1},
        {file: package["docker-registry"].path, type: 2}
    ];
    compress(file,tarName,suffix);
    setTimeout(function(){
        // let rs = fs.readFileSync("./docker/"+ tarName +"." + suffix,"binary");
        fs.readFile("./docker/"+ tarName + "." + suffix, function(err, data) {
            if(err === null) {
                buildImage(name,data,baseUrl)
            } else {
                console.log("文件读取失败")
            }
        })
    },3000)
} else if (type === "push") {
    const {Base64} = require("js-base64");
    let auth = Base64.encode(JSON.stringify(config));
    pushImage(name,auth,baseUrl);
} else {
    console.log("error: 编译类型错误");
}


